let currentCity = {
  name: '北京',
  id: '101010100',
  lat: 39.9042,
  lon: 116.4074
};

// 和风天气API配置 - 完整版
const HEFENG_API = {
  key: '2e5a756ffeed4d899736732f258b0aed', // 请替换为您的和风天气API Key
  baseUrl: 'https://m27p42erbd.re.qweatherapi.com', // 请替换为您的和风天气API Host
  
  // 各接口端点
  endpoints: {
    current: '/v7/weather/now',           // 实时天气
    forecast: '/v7/weather/7d',           // 7天预报
    hourly: '/v7/weather/24h',            // 逐小时预报 - 新增
    indices: '/v7/indices/1d',            // 生活指数 - 新增
    geoLookup: '/geo/v2/city/lookup'      // 城市搜索
  }
};

// DOM元素引用
let domElements = {};

// 初始化DOM元素引用
function initDOMElements() {
  domElements = {
    // 搜索相关
    citySearch: document.getElementById('city-search'),
    searchResults: document.getElementById('search-results'),
    
    // 加载指示器
    loading: document.getElementById('loading'),
    
    // 天气信息显示
    currentLocation: document.getElementById('current-location'),
    currentWeatherIcon: document.getElementById('current-weather-icon'),
    currentTemp: document.getElementById('current-temp'),
    currentDesc: document.getElementById('current-desc'),
    currentDetail: document.getElementById('current-detail'),
    currentWind: document.getElementById('current-wind'),
    currentHumidity: document.getElementById('current-humidity'),
    forecastContainer: document.getElementById('forecast-container'),
    future30dText: document.getElementById('future-30d-text'),
    
    // 调试信息
    debugInfo: document.getElementById('debug-info'),
    
    // 详情页元素
    weatherDetailPage: document.getElementById('weather-detail-page'),
    backButton: document.getElementById('back-button'),
    detailLocation: document.getElementById('detail-location'),
    detailTemp: document.getElementById('detail-temp'),
    detailWeather: document.getElementById('detail-weather'),
    detailTempRange: document.getElementById('detail-temp-range'),
    hourlyContainer: document.getElementById('hourly-container'),
    detailsGrid: document.getElementById('details-grid'),
    indexContainer: document.getElementById('index-container'),
    currentWeatherClickable: document.getElementById('current-weather-clickable'),

    // 轮播图相关元素
    weatherCarousel: document.getElementById('weather-carousel'),
    carouselContainer: document.getElementById('carousel-container'),
    carouselDots: document.getElementById('carousel-dots'),
    prevBtn: document.getElementById('prev-btn'),
    nextBtn: document.getElementById('next-btn'),
    carouselWeatherDesc: document.getElementById('carousel-weather-desc'),
    carouselTimeDesc: document.getElementById('carousel-time-desc')
  };
}

// 调试信息
function debugLog(message) {
  console.log(message);
  if (domElements.debugInfo) {
    domElements.debugInfo.innerHTML = `<div>${new Date().toLocaleTimeString()}: ${message}</div>`;
  }
}

// 初始化天气数据
document.addEventListener('DOMContentLoaded', function() {
  // 首先初始化DOM元素引用
  initDOMElements();
  
  debugLog('页面加载完成，开始初始化...');
  
  // 检查API配置
  if (HEFENG_API.key === 'YOUR_API_KEY' || HEFENG_API.baseUrl === 'https://YOUR_API_HOST') {
    debugLog('警告：请先配置和风天气API密钥和Host');
    if (domElements.loading) {
      domElements.loading.textContent = '请先配置和风天气API密钥和Host';
    }
    return;
  }
  
  loadWeatherData(currentCity);
  setupEventListeners();
});

// 设置事件监听器
function setupEventListeners() {
  debugLog('设置事件监听器...');
  
  // 搜索功能
  if (domElements.citySearch && domElements.searchResults) {
    // 输入时搜索城市
    let searchTimeout;
    domElements.citySearch.addEventListener('input', function() {
      clearTimeout(searchTimeout);
      const query = this.value.trim();
      
      if (query.length < 2) {
        domElements.searchResults.style.display = 'none';
        return;
      }
      
      searchTimeout = setTimeout(() => {
        searchCities(query);
      }, 300);
    });
    
    // 点击外部关闭搜索结果
    document.addEventListener('click', function(e) {
      if (!domElements.citySearch.contains(e.target) && !domElements.searchResults.contains(e.target)) {
        domElements.searchResults.style.display = 'none';
      }
    });
  }
  
  // 详情页事件
  if (domElements.currentWeatherClickable) {
    domElements.currentWeatherClickable.addEventListener('click', showWeatherDetail);
  }
  
  if (domElements.backButton) {
    domElements.backButton.addEventListener('click', hideWeatherDetail);
  }

  // 轮播图控制事件
  if (domElements.prevBtn && domElements.nextBtn) {
    domElements.prevBtn.addEventListener('click', showPrevSlide);
    domElements.nextBtn.addEventListener('click', showNextSlide);
  }
  
  debugLog('事件监听器设置完成');
}

// 搜索城市
async function searchCities(query) {
  if (!domElements.searchResults) return;
  
  debugLog(`搜索城市: ${query}`);
  
  try {
    // 调用和风天气城市搜索API
    const url = `${HEFENG_API.baseUrl}${HEFENG_API.endpoints.geoLookup}?location=${encodeURIComponent(query)}&key=${HEFENG_API.key}`;
    debugLog(`请求URL: ${url}`);
    
    const response = await fetch(url);
    
    if (!response.ok) {
      throw new Error(`HTTP错误: ${response.status} ${response.statusText}`);
    }
    
    const data = await response.json();
    debugLog(`API响应: ${JSON.stringify(data)}`);
    
    if (data.code === '200' && data.location && data.location.length > 0) {
      // 显示搜索结果
      domElements.searchResults.innerHTML = '';
      data.location.forEach(city => {
        const item = document.createElement('div');
        item.className = 'search-result-item';
        item.textContent = `${city.name}, ${city.adm2}, ${city.adm1}`;
        item.addEventListener('click', () => {
          selectCity({
            name: city.name,
            id: city.id,
            lat: parseFloat(city.lat),
            lon: parseFloat(city.lon),
            adm2: city.adm2, // 保存地级市信息
            adm1: city.adm1  // 保存省份信息
          });
          domElements.searchResults.style.display = 'none';
          if (domElements.citySearch) {
            domElements.citySearch.value = '';
          }
        });
        domElements.searchResults.appendChild(item);
      });
      domElements.searchResults.style.display = 'block';
      debugLog(`找到 ${data.location.length} 个城市`);
    } else {
      console.error('API返回错误:', data);
      let errorMessage = '未找到相关城市';
      if (data.code === '204') {
        errorMessage = '未找到匹配的城市';
      } else if (data.code === '401') {
        errorMessage = 'API密钥错误';
      } else if (data.code === '404') {
        errorMessage = 'API地址错误';
      } else if (data.code === '429') {
        errorMessage = '请求频率超限';
      }
      domElements.searchResults.innerHTML = `<div class="search-result-item">${errorMessage}</div>`;
      domElements.searchResults.style.display = 'block';
      debugLog(`城市搜索失败: ${errorMessage}`);
    }
  } catch (error) {
    console.error('搜索城市失败:', error);
    domElements.searchResults.innerHTML = `<div class="search-result-item">搜索失败: ${error.message}</div>`;
    domElements.searchResults.style.display = 'block';
    debugLog(`搜索城市异常: ${error.message}`);
  }
}

// 选择城市
function selectCity(city) {
  debugLog(`选择城市: ${city.name}`);
  currentCity = city;
  loadWeatherData(city);
}

// 加载天气数据 - 更新版本
async function loadWeatherData(city) {
  if (!domElements.loading) {
    console.error('找不到loading元素');
    return;
  }
  
  domElements.loading.style.display = 'block';
  domElements.loading.textContent = `正在获取${city.name}的天气数据...`;
  debugLog(`开始加载 ${city.name} 的天气数据`);
  
  try {
    // 并行获取所有天气数据
    const [currentWeather, forecast, hourlyForecast, indices] = await Promise.all([
      fetchCurrentWeather(city.id),
      fetchWeatherForecast(city.id),
      fetchHourlyForecast(city.id),      // 新增
      fetchLivingIndices(city.id)        // 新增
    ]);
    
    // 保存数据到全局变量，供详情页使用
    window.currentWeatherData = {
      current: currentWeather,
      forecast: forecast,
      hourly: hourlyForecast,
      indices: indices,
      city: city
    };
    
    // 更新左侧天气信息
    updateWeatherInfo(currentWeather, forecast, city);
    
    // 隐藏加载提示
    domElements.loading.style.display = 'none';
    debugLog(`${city.name} 天气数据加载成功`);
  } catch (error) {
    console.error('加载天气数据失败:', error);
    domElements.loading.textContent = `加载失败: ${error.message}`;
    debugLog(`天气数据加载失败: ${error.message}`);
  }
}

// 获取实时天气
async function fetchCurrentWeather(locationId) {
  debugLog(`获取实时天气，位置ID: ${locationId}`);
  const url = `${HEFENG_API.baseUrl}${HEFENG_API.endpoints.current}?location=${locationId}&key=${HEFENG_API.key}`;
  debugLog(`请求URL: ${url}`);
  
  const response = await fetch(url);
  
  if (!response.ok) {
    throw new Error(`HTTP错误: ${response.status} ${response.statusText}`);
  }
  
  const data = await response.json();
  debugLog(`实时天气API响应: ${JSON.stringify(data)}`);
  
  if (data.code === '200') {
    return data;
  } else {
    throw new Error(`API错误: ${data.code} - ${data.message}`);
  }
}

// 获取天气预报
async function fetchWeatherForecast(locationId) {
  debugLog(`获取天气预报，位置ID: ${locationId}`);
  const url = `${HEFENG_API.baseUrl}${HEFENG_API.endpoints.forecast}?location=${locationId}&key=${HEFENG_API.key}`;
  debugLog(`请求URL: ${url}`);
  
  const response = await fetch(url);
  
  if (!response.ok) {
    throw new Error(`HTTP错误: ${response.status} ${response.statusText}`);
  }
  
  const data = await response.json();
  debugLog(`天气预报API响应: ${JSON.stringify(data)}`);
  
  if (data.code === '200') {
    return data;
  } else {
    throw new Error(`API错误: ${data.code} - ${data.message}`);
  }
}

// 获取逐小时天气预报 - 新增
async function fetchHourlyForecast(locationId) {
  debugLog(`获取逐小时预报，位置ID: ${locationId}`);
  const url = `${HEFENG_API.baseUrl}${HEFENG_API.endpoints.hourly}?location=${locationId}&key=${HEFENG_API.key}`;
  debugLog(`请求URL: ${url}`);
  
  const response = await fetch(url);
  
  if (!response.ok) {
    throw new Error(`HTTP错误: ${response.status} ${response.statusText}`);
  }
  
  const data = await response.json();
  debugLog(`逐小时预报API响应: ${JSON.stringify(data)}`);
  
  if (data.code === '200') {
    return data;
  } else {
    throw new Error(`API错误: ${data.code} - ${data.message}`);
  }
}

// 获取生活指数 - 新增
async function fetchLivingIndices(locationId) {
  debugLog(`获取生活指数，位置ID: ${locationId}`);
  const url = `${HEFENG_API.baseUrl}${HEFENG_API.endpoints.indices}?type=0&location=${locationId}&key=${HEFENG_API.key}`;
  debugLog(`请求URL: ${url}`);
  
  const response = await fetch(url);
  
  if (!response.ok) {
    throw new Error(`HTTP错误: ${response.status} ${response.statusText}`);
  }
  
  const data = await response.json();
  debugLog(`生活指数API响应: ${JSON.stringify(data)}`);
  
  if (data.code === '200') {
    return data;
  } else {
    throw new Error(`API错误: ${data.code} - ${data.message}`);
  }
}

// 更新左侧天气信息
function updateWeatherInfo(currentData, forecastData, city) {
  const current = currentData.now;



  // 更新当前天气 - 添加安全检查
  if (domElements.currentLocation) {
    domElements.currentLocation.textContent = `${city.name}, ${getAdmName(city)}`;
  }
  
  if (domElements.currentWeatherIcon) {
    domElements.currentWeatherIcon.innerHTML = getWeatherIcon(current.text, isDayTime());
  }
  
  if (domElements.currentTemp) {
    domElements.currentTemp.textContent = `${current.temp}°`;
  }
  
  if (domElements.currentDesc) {
    domElements.currentDesc.textContent = current.text;
  }
  
  if (domElements.currentDetail) {
    domElements.currentDetail.textContent = `当前温度${current.temp}°，${current.text}，${current.windDir}${current.windScale}级`;
  }
  
  if (domElements.currentWind) {
    domElements.currentWind.textContent = `${current.windScale}级 ${current.windDir}`;
  }
  
  if (domElements.currentHumidity) {
    domElements.currentHumidity.textContent = `${current.humidity}% 相对湿度`;
  }
  
  // 更新预报
  if (domElements.forecastContainer) {
    domElements.forecastContainer.innerHTML = '';
    
    forecastData.daily.forEach((day, index) => {
      if (index >= 5) return; // 只显示5天
      
      const forecastItem = document.createElement('div');
      forecastItem.className = 'forecast-item';
      
      const date = new Date();
      date.setDate(date.getDate() + index);
      const dateStr = index === 0 ? '今天' : formatDate(date);
      
      forecastItem.innerHTML = `
        <div class="date">${dateStr}</div>
        <div class="weather">${getWeatherIcon(day.textDay, true)}</div>
        <div class="temp-range">${day.tempMin}° ~ ${day.tempMax}°</div>
      `;
      domElements.forecastContainer.appendChild(forecastItem);
    });
  }
  
  // 更新30天预报
  if (domElements.future30dText) {
    domElements.future30dText.textContent = '未来30天预报需要付费API支持，如需使用请联系和风天气获取相应权限。';
  }
  // 更新轮播图 - 添加这行代码
  updateCarousel(current.text);
}

// 获取行政区域名称 - 修复县级城市显示问题
function getAdmName(city) {
  // 如果是直辖市，直接显示"中国"
  const directCities = ['北京', '上海', '天津', '重庆'];
  if (directCities.includes(city.name)) {
    return '中国';
  }
  
  // 如果有adm2(地级市)且不为空，则显示adm2
  if (city.adm2 && city.adm2.trim() !== '') {
    // 检查adm2是否与城市名相同，避免重复显示
    if (city.adm2 === city.name) {
      return `${city.adm1}, 中国`;
    }
    return `${city.adm2}, ${city.adm1}, 中国`;
  }
  
  // 如果没有adm2，则只显示adm1(省份)
  return `${city.adm1}, 中国`;
}

// 根据天气状况和时间获取和风天气图标
function getWeatherIcon(weatherText, isDay = true) {
  // 天气现象与和风天气图标代码的映射关系
  const iconCodeMap = {
    '晴': isDay ? '100' : '150',
    '多云': isDay ? '101' : '151',
    '少云': isDay ? '102' : '152',
    '晴间多云': isDay ? '103' : '153',
    '阴': '104',
    '阵雨': isDay ? '300' : '350',
    '强阵雨': isDay ? '301' : '351',
    '雷阵雨': '302',
    '强雷阵雨': '303',
    '雷阵雨伴有冰雹': '304',
    '小雨': '305',
    '中雨': '306',
    '大雨': '307',
    '极端降雨': '308',
    '毛毛雨/细雨': '309',
    '暴雨': '310',
    '大暴雨': '311',
    '特大暴雨': '312',
    '冻雨': '313',
    '小到中雨': '314',
    '中到大雨': '315',
    '大到暴雨': '316',
    '暴雨到大暴雨': '317',
    '大暴雨到特大暴雨': '318',
    '雨': '399',
    '小雪': '400',
    '中雪': '401',
    '大雪': '402',
    '暴雪': '403',
    '雨夹雪': '404',
    '雨雪天气': '405',
    '阵雨夹雪': isDay ? '406' : '456',
    '阵雪': isDay ? '407' : '457',
    '小到中雪': '408',
    '中到大雪': '409',
    '大到暴雪': '410',
    '雪': '499',
    '薄雾': '500',
    '雾': '501',
    '霾': '502',
    '扬沙': '503',
    '浮尘': '504',
    '沙尘暴': '507',
    '强沙尘暴': '508',
    '浓雾': '509',
    '强浓雾': '510',
    '中度霾': '511',
    '重度霾': '512',
    '严重霾': '513',
    '大雾': '514',
    '特强浓雾': '515',
    '热': '900',
    '冷': '901',
    '未知': '999'
  };

  const code = iconCodeMap[weatherText] || '999';
  return `<i class="qi-${code}"></i>`;
}

// 简单的昼夜判断函数
function isDayTime() {
  const hour = new Date().getHours();
  return hour > 6 && hour < 10;
}

// 格式化日期
function formatDate(date) {
  const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const weekday = weekdays[date.getDay()];
  
  return `${weekday} ${month}月${day}日`;
}

// 显示天气详情页
async function showWeatherDetail() {
  debugLog('显示天气详情页');
  
  try {
    // 显示加载状态
    if (domElements.weatherDetailPage) {
      domElements.weatherDetailPage.classList.add('active');
    }
    
    // 使用已加载的数据，避免重复调用API
    if (window.currentWeatherData) {
      updateDetailPageWithData(window.currentWeatherData);
    } else {
      // 如果没有数据，重新加载
      await loadWeatherData(currentCity);
      if (window.currentWeatherData) {
        updateDetailPageWithData(window.currentWeatherData);
      }
    }
    
  } catch (error) {
    console.error('加载详情页数据失败:', error);
    debugLog(`详情页数据加载失败: ${error.message}`);
    // 显示错误信息
    if (domElements.hourlyContainer) {
      domElements.hourlyContainer.innerHTML = '<div class="error-message">数据加载失败</div>';
    }
  }
}

// 隐藏天气详情页
function hideWeatherDetail() {
  if (domElements.weatherDetailPage) {
    domElements.weatherDetailPage.classList.remove('active');
  }
}

// 使用数据更新详情页 - 新增函数
function updateDetailPageWithData(weatherData) {
  const { current, forecast, hourly, indices, city } = weatherData;
  
  // 更新基本信息
  updateDetailBasicInfo(current, forecast, city);
  
  // 更新逐小时预报
  updateHourlyForecast(hourly);
  
  // 更新天气详情
  updateWeatherDetails(current);
  
  // 更新生活指数
  updateLivingIndices(indices);
}

// 更新详情页基本信息 - 更新版本
function updateDetailBasicInfo(currentData, forecastData, city) {
  const current = currentData.now;
  const todayForecast = forecastData.daily[0];
  
  if (domElements.detailLocation) {
    domElements.detailLocation.textContent = `${city.name}, ${getAdmName(city)}`;
  }
  if (domElements.detailTemp) {
    domElements.detailTemp.textContent = `${current.temp}°`;
  }
  if (domElements.detailWeather) {
    domElements.detailWeather.innerHTML = getWeatherIcon(current.text, isDayTime()) + ' ' + current.text;
  }
  if (domElements.detailTempRange && todayForecast) {
    domElements.detailTempRange.textContent = `最高 ${todayForecast.tempMax}° 最低 ${todayForecast.tempMin}°`;
  }
}

// 更新逐小时预报显示 - 更新版本
function updateHourlyForecast(hourlyData) {
  if (!domElements.hourlyContainer || !hourlyData.hourly) return;
  
  domElements.hourlyContainer.innerHTML = '';
  
  // 只显示未来24小时中的前12小时
  hourlyData.hourly.slice(0, 12).forEach(hour => {
    const hourItem = document.createElement('div');
    hourItem.className = 'hourly-item';
    
    const time = new Date(hour.fxTime);
    const timeStr = `${time.getHours()}时`;
    const isDay = time.getHours() >= 6 && time.getHours() <= 18;
    
    hourItem.innerHTML = `
      <div class="hourly-time">${timeStr}</div>
      <div class="hourly-icon">${getWeatherIcon(hour.text, isDay)}</div>
      <div class="hourly-temp">${hour.temp}°</div>
      <div class="hourly-pop">${hour.pop || 0}%</div>
    `;
    
    domElements.hourlyContainer.appendChild(hourItem);
  });
}

// 更新天气详情 - 更新版本（使用真实数据）
function updateWeatherDetails(currentData) {
  if (!domElements.detailsGrid || !currentData.now) return;
  
  const now = currentData.now;
  
  const details = [
    { icon: '💨', label: '风速', value: `${now.windScale}级 ${now.windDir}` },
    { icon: '💧', label: '湿度', value: `${now.humidity}%` },
    { icon: '🔽', label: '气压', value: `${now.pressure || '--'} hPa` },
    { icon: '👁️', label: '能见度', value: `${now.vis || '--'} km` },
    { icon: '🌡️', label: '体感温度', value: `${now.feelsLike || now.temp}°` },
    { icon: '⏱️', label: '更新时间', value: formatUpdateTime(currentData.updateTime) }
  ];
  
  domElements.detailsGrid.innerHTML = '';
  
  details.forEach(detail => {
    const detailItem = document.createElement('div');
    detailItem.className = 'detail-item';
    
    detailItem.innerHTML = `
      <div class="icon">${detail.icon}</div>
      <div class="label">${detail.label}</div>
      <div class="value">${detail.value}</div>
    `;
    
    domElements.detailsGrid.appendChild(detailItem);
  });
}

// 更新生活指数显示
function updateLivingIndices(indicesData) {
  if (!domElements.indexContainer || !indicesData.daily) return;
  
  domElements.indexContainer.innerHTML = '';
  
  // 只显示前6个指数
  indicesData.daily.slice(0, 6).forEach(index => {
    const indexItem = document.createElement('div');
    indexItem.className = 'index-item';
    
    const indexIcon = getIndexIcon(index.name);
    
    indexItem.innerHTML = `
      <div class="index-info">
        <div class="index-icon">${indexIcon}</div>
        <div class="index-name">${index.name}</div>
      </div>
      <div class="index-level">${index.category}</div>
    `;
    
    domElements.indexContainer.appendChild(indexItem);
  });
}

// 格式化更新时间 - 新增辅助函数
function formatUpdateTime(updateTime) {
  if (!updateTime) return '--';
  const time = new Date(updateTime);
  return `${time.getHours()}:${time.getMinutes().toString().padStart(2, '0')}`;
}

// 获取生活指数图标
function getIndexIcon(indexName) {
  const iconMap = {
    '穿衣指数': '👕',
    '运动指数': '🏃',
    '洗车指数': '🚗',
    '紫外线指数': '☀️',
    '感冒指数': '🤧',
    '空气污染扩散条件指数': '🌫️',
    '舒适度指数': '😊',
    '旅游指数': '🏞️',
    '钓鱼指数': '🎣'
  };
  
  return iconMap[indexName] || '📊';
}
// 轮播图状态
let carouselState = {
  currentIndex: 0,
  totalSlides: 0,
  autoPlayInterval: null,
  currentWeather: '',
  isDayTime: true
};

// 统一的备用图片（渐变背景，无文字）
const UNIFIED_FALLBACK = '';

// 天气图片映射配置
const WEATHER_IMAGES = {
  '晴': {
    day: [
      'images/sunny/day1.jpg',
      'images/sunny/day2.jpg', 
      'images/sunny/day3.jpg',
      'images/sunny/day4.jpg'
    ],
    night: [
      'images/sunny/night1.jpg',
      'images/sunny/night2.jpg',
      'images/sunny/night3.jpg', 
      'images/sunny/night4.jpg'
    ]
  },
  '多云': {
    day: [
      'images/cloudy/day1.jpg',
      'images/cloudy/day2.jpg',
      'images/cloudy/day3.jpg',
      'images/cloudy/day4.jpg'
    ],
    night: [
      'images/cloudy/night1.jpg',
      'images/cloudy/night2.jpg',
      'images/cloudy/night3.jpg',
      'images/cloudy/night4.jpg'
    ]
  },
  '阴': {
    day: [
      'images/overcast/day1.jpg',
      'images/overcast/day2.jpg',
      'images/overcast/day3.jpg',
      'images/overcast/day4.jpg'
    ],
    night: [
      'images/overcast/night1.jpg',
      'images/overcast/night2.jpg',
      'images/overcast/night3.jpg',
      'images/overcast/night4.jpg'
    ]
  },
  '雨': {
    day: [
      'images/rainy/day1.jpg',
      'images/rainy/day2.jpg',
      'images/rainy/day3.jpg',
      'images/rainy/day4.jpg'
    ],
    night: [
      'images/rainy/night1.jpg',
      'images/rainy/night2.jpg',
      'images/rainy/night3.jpg',
      'images/rainy/night4.jpg'
    ]
  },
  '雪': {
    day: [
      'images/snowy/day1.jpg',
      'images/snowy/day2.jpg',
      'images/snowy/day3.jpg',
      'images/snowy/day4.jpg'
    ],
    night: [
      'images/snowy/night1.jpg',
      'images/snowy/night2.jpg',
      'images/snowy/night3.jpg',
      'images/snowy/night4.jpg'
    ]
  },
  '雾': {
    day: [
      'images/foggy/day1.jpg',
      'images/foggy/day2.jpg',
      'images/foggy/day3.jpg',
      'images/foggy/day4.jpg'
    ],
    night: [
      'images/foggy/night1.jpg',
      'images/foggy/night2.jpg',
      'images/foggy/night3.jpg',
      'images/foggy/night4.jpg'
    ]
  },
  '霾': {
    day: [
      'images/haze/day1.jpg',
      'images/haze/day2.jpg',
      'images/haze/day3.jpg',
      'images/haze/day4.jpg'
    ],
    night: [
      'images/haze/night1.jpg',
      'images/haze/night2.jpg',
      'images/haze/night3.jpg',
      'images/haze/night4.jpg'
    ]
  }

};

// 默认图片（用于天气类型不匹配时）
const DEFAULT_IMAGES = {
  day: [
    'images/default/day1.jpg',
    'images/default/day2.jpg',
    'images/default/day3.jpg',
    'images/default/day4.jpg'
  ],
  night: [
    'images/default/night1.jpg',
    'images/default/night2.jpg',
    'images/default/night3.jpg',
    'images/default/night4.jpg'
  ]
};

// 更新轮播图
function updateCarousel(weatherText) {
  debugLog(`更新轮播图，天气: ${weatherText}`);
  
  if (!domElements.carouselContainer) return;
  
  // 确定天气类型（简化处理）
  let weatherType = '晴';
  if (weatherText.includes('云')) weatherType = '多云';
  if (weatherText.includes('阴')) weatherType = '阴';
  if (weatherText.includes('雨')) weatherType = '雨';
  if (weatherText.includes('雪')) weatherType = '雪';
  if (weatherText.includes('雾')) weatherType = '雾';
  
  
  const isDay = isDayTime();
  const timeKey = isDay ? 'day' : 'night';
  
  // 获取对应图片
  const imageSet = WEATHER_IMAGES[weatherType]?.[timeKey] || DEFAULT_IMAGES[timeKey];
  
  // 更新状态
  carouselState.currentWeather = weatherText;
  carouselState.isDayTime = isDay;
  carouselState.totalSlides = imageSet.length;
  
  // 清空现有内容
  domElements.carouselContainer.innerHTML = '';
  if (domElements.carouselDots) {
    domElements.carouselDots.innerHTML = '';
  }
  
  // 创建轮播图片
  imageSet.forEach((imageSrc, index) => {
    const slide = document.createElement('div');
    slide.className = `carousel-slide ${index === 0 ? 'active' : ''}`;
    slide.innerHTML = `
      <img src="${imageSrc}" alt="${weatherText} ${timeKey === 'day' ? '白天' : '夜晚'}" class="carousel-image" 
           onerror="this.src='${UNIFIED_FALLBACK}'">
    `;
    domElements.carouselContainer.appendChild(slide);
    
    // 创建指示点
    if (domElements.carouselDots) {
      const dot = document.createElement('div');
      dot.className = `carousel-dot ${index === 0 ? 'active' : ''}`;
      dot.addEventListener('click', () => showSlide(index));
      domElements.carouselDots.appendChild(dot);
    }
  });
  
  // 更新覆盖层信息
  if (domElements.carouselWeatherDesc) {
    domElements.carouselWeatherDesc.textContent = weatherText;
  }
  if (domElements.carouselTimeDesc) {
    domElements.carouselTimeDesc.textContent = isDay ? '白天' : '夜晚';
  }
  
  // 启动自动轮播
  startAutoPlay();
  
  debugLog(`轮播图更新完成，共 ${imageSet.length} 张图片`);
}

// 显示指定幻灯片
function showSlide(index) {
  if (!domElements.carouselContainer) return;
  
  const slides = domElements.carouselContainer.querySelectorAll('.carousel-slide');
  const dots = domElements.carouselDots?.querySelectorAll('.carousel-dot');
  
  if (slides.length === 0) return;
  
  // 更新当前索引
  carouselState.currentIndex = index;
  
  // 更新幻灯片位置
  domElements.carouselContainer.style.transform = `translateX(-${index * 100}%)`;
  
  // 更新激活状态
  slides.forEach((slide, i) => {
    slide.classList.toggle('active', i === index);
  });
  
  // 更新指示点
  if (dots) {
    dots.forEach((dot, i) => {
      dot.classList.toggle('active', i === index);
    });
  }
}

// 显示下一张幻灯片
function showNextSlide() {
  const nextIndex = (carouselState.currentIndex + 1) % carouselState.totalSlides;
  showSlide(nextIndex);
  resetAutoPlay(); // 重置自动播放计时器
}

// 显示上一张幻灯片
function showPrevSlide() {
  const prevIndex = (carouselState.currentIndex - 1 + carouselState.totalSlides) % carouselState.totalSlides;
  showSlide(prevIndex);
  resetAutoPlay(); // 重置自动播放计时器
}

// 启动自动播放
function startAutoPlay() {
  stopAutoPlay(); // 先停止现有的自动播放
  carouselState.autoPlayInterval = setInterval(showNextSlide, 5000); // 5秒切换一次
}

// 停止自动播放
function stopAutoPlay() {
  if (carouselState.autoPlayInterval) {
    clearInterval(carouselState.autoPlayInterval);
    carouselState.autoPlayInterval = null;
  }
}

// 重置自动播放
function resetAutoPlay() {
  stopAutoPlay();
  startAutoPlay();
}

// 在页面失去焦点时停止自动播放，获得焦点时重新开始
document.addEventListener('visibilitychange', function() {
  if (document.hidden) {
    stopAutoPlay();
  } else {
    startAutoPlay();
  }
});